package com.linwen.excise.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName _54螺旋矩阵
 * @Description TODO
 * @Author zero
 * @DATE 2024/4/21 12:12 PM
 * @Version 1.0
 */
public class _54螺旋矩阵 {
    public static void main(String[] args) {
        //int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(spiralOrder(matrix));
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int top = 0,bottom = m-1,left = 0,right = n-1;
        int count = (Math.min(m,n)+1)/2;
        List<Integer> res = new ArrayList<>();
        for (int temp = 0; temp < count; temp++) {
            // 左到右  到头
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            // 上到下  到头
            for (int i = top+1; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            if(right>left&&bottom>top){
                // 右到左  不到头
                for (int i = right-1; i > left; i--) {
                    res.add(matrix[bottom][i]);
                }
                // 下到上  不到头
                for (int i = bottom; i > top; i--) {
                    res.add(matrix[i][left]);
                }
            }
            top++;
            right--;
            bottom--;
            left++;
        }
        return res;
    }
}
